/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import { PoolConstant, WatchEvent } from '@ohos/hvigor';
import { getPkgName2SourceRootsMap, LogEvent, ProjectConfig, watch } from '@ohos/hvigor-arkts-compose';
import { parentPort, workerData } from 'worker_threads';

import { OhosLogger } from '../../utils/log/ohos-logger.js';

import { errorCallback } from './job.js';
import { generateLoaderEnv, onTerminateWorker, setLogLevel } from './util.js';

const updatePkgName2SourceRoots = onTerminateWorker().updatePkgName2SourceRoots;

setLogLevel(workerData.logLevel);
const logger: OhosLogger = OhosLogger.getLogger('Hot_Reload');
const projectConfig: ProjectConfig = workerData.projectConfig;
generateLoaderEnv(projectConfig);

const onBuildFailed = (e?: Error | string) => {
  const reason = e instanceof Error ? e.message : e || 'unknown error';
  parentPort!.postMessage({ event: PoolConstant.WORK_ERROR, error: reason });
};

watch(
  projectConfig,
  errorCallback,
  (logs: LogEvent[], lastReUsedFiles?: Set<string>) => {
    updatePkgName2SourceRoots(getPkgName2SourceRootsMap(projectConfig));
    if (lastReUsedFiles) {
      logs.length = 0;
    } else {
      parentPort!.postMessage({ type: WatchEvent.WATCH_LOG, content: logs });
    }
  },
  parentPort!,
  logger,
)
  .then((arkCompileResult) => {
    if (!arkCompileResult.isSuccess) {
      onBuildFailed(arkCompileResult.error);
      return;
    }
    parentPort!.postMessage({ event: PoolConstant.WORK_DONE, returnVal: arkCompileResult.compileEvents });
  })
  .catch((reason) => {
    onBuildFailed(reason);
  })
  .finally(() => {
    logger.debug('Ark compile finished.');
  }); // 启用 rollup watch
